import base64
import pickle
from django_redis import get_redis_connection


def merge_carts_cookie_redis(request, response, user):
    cookie_carts = request.COOKIES.get('carts')

    if cookie_carts:
        cookie_carts_bytes = cookie_carts.encode()
        cookie_carts_base64 = base64.b64decode(cookie_carts_bytes)
        cookie_dict = pickle.loads(cookie_carts_base64)
    else:
        return response

    new_dict = {}
    cookie_selected_add = []
    cookie_selected_rem = []

    for sku_id, cart_dict in cookie_dict.items():
        new_dict[sku_id] = cart_dict['count']
        if cart_dict['selected']:
            cookie_selected_add.append(sku_id)
        else:
            cookie_selected_rem.append(sku_id)

    redis_conn = get_redis_connection('carts')
    pl = redis_conn.pipeline()

    pl.hmset('carts_%s' % user.id, new_dict)

    if cookie_selected_add:
        pl.sadd('selected_%s' % user.id, *cookie_selected_add)

    if cookie_selected_rem:
        pl.srem('selected_%s' % user.id, *cookie_selected_rem)

    pl.execute()

    response.delete_cookie('carts')

    return response
